from fastapi import APIRouter, Depends, Header
from typing import Union, List, Annotated
from datetime import datetime
from schema.blog import SearchBlogs
from model.blog import Blog, BlogCategory
from schema.response.baseResponse import BaseResponse, CustomException
from schema.response.blogResponse import BlogResponse, BlogCategoryResponse
from server.blog import get_blog_by_category, get_blog_category, get_blog_detail, get_today_blog_in_log
from server.goldCoins import browse_blog_gold_coins_calculate
from utils.middleware import decode_token_by_head



router = APIRouter(
    prefix="/blogs/v1",
    tags=["blogs"],
    dependencies=[],
    responses={404: {"description": "Not found"}}
)


@router.get("/blogType", response_model=BaseResponse[List[BlogCategoryResponse]], summary = "获取博客类型列表")
async def get_blog_category_list():
    blog_category: List[BlogCategory] = await get_blog_category()
    return BaseResponse.success(blog_category)


@router.get("/blogs", response_model=BaseResponse[List[BlogResponse]], summary = "根据类型获取博客列表")
async def search_blog(blog_category_id: int, title: str | None = None):
    blogs = await get_blog_by_category(blog_category_id, title)
    return BaseResponse.success(blogs)


@router.get("/{blog_id: int}", response_model=BaseResponse[BlogResponse], summary = "查看博客内容，消耗积分，一天只消耗一次, 积分不足无法查看")
async def blog_detail(blog_id: int, token: str = Depends(decode_token_by_head)):
    blog = await get_blog_detail(blog_id)
    if not blog:
        raise CustomException(code=404, msg="博客不存在")
    blog_log = await get_today_blog_in_log(token.get("id"), blog_id)
    if not blog_log:
        # 查看博客消耗积分
        await browse_blog_gold_coins_calculate(token.get("id"), blog_id)
    return BaseResponse.success(blog)